﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Specialized;
using MShop.Core.Service.Search;
using MShop.Core.Util;

namespace MShop.Core.Domain
{
    
    [MetadataType(typeof(Product_Validation))]
    public partial class Product: ISearchableContent
    {
        public Product()
        {
            this.DeListTime = DateTime.Now.AddDays(365);
            this.ListTime = DateTime.Now;
            HasDiscount = false;
            this.IsVirtual = false;
            this.Status = 1;
            this.CollectNum = 1;
            this.Created = DateTime.Now;
            this.StandCode = DateTime.Now.ToString("yyyyMMddHHmmss");
            this.IsPackage = true;
            IsPublish = false;
            Unit = "瓶";
             
        }

        public string GetImageUrl(string domain)
        {

            if (this.ImageUrl.ToLowerInvariant().IndexOf("http://") == -1)
            {
                if (domain.Last() == '/')
                {
                    return string.Concat(domain, ImageUrl);
                }
                else
                {
                    return string.Concat(domain, "/", ImageUrl);
                }
            }
            return ImageUrl;

        }

        public string ImageUrl
        {
            get
            {
                if (string.IsNullOrEmpty(this.PicUrl))
                {
                    return string.Empty; ;
                }
                return "/uploads/" + PicUrl;// this.Face.Split('/')[0] + "/thumb_" + this.Face.Split('/')[1];
            }
        }

        public string ThumbImageUrl
        {
            get
            {
                if (string.IsNullOrEmpty(this.PicUrl))
                {
                    return PicUrl;
                }
                try
                {
                    return "/uploads/" + this.PicUrl.Split('/')[0] + "/thumb_" + this.PicUrl.Split('/')[1];
                }
                catch
                {
                    return string.Empty;
                }
            }
        }


        public string GetThumbImageUrl(string domain)
        {
            
                if (this.ThumbImageUrl.ToLowerInvariant().IndexOf("http://") == -1)
                {
                    if(domain.Last()=='/')
                    {
                        return string.Concat(domain,ThumbImageUrl);
                    }
                    else
                    {
                        return string.Concat(domain,"/",ThumbImageUrl);
                    }
                }
                return ThumbImageUrl ;
            
        }


        public int PropertyCount
        {
            get;
            set;
        }


        public bool HasColorProperty
        {
            get
            {
               return this.ProductSkuProp.Count(x => x.ItemCatProp.ItemProp.IsColorProp) > 0;
            }
        }

        public IList<string> ProductSkuPropValues
        {
            get
            {
                IList<string> sc = new List<string>();
                IDictionary<string, ICollection<ProductSkuProp>> dict = new Dictionary<string, ICollection<ProductSkuProp>>();

                ILookup<int, string> lookup = this.ProductSkuProp.ToLookup(x => x.ItemCatPropId, x =>string.Concat(x.ItemCatPropId,":",x.PropValue));

                foreach (IGrouping<int, string> item in lookup)
                {
                    var v = lookup[item.Key];
                    sc.Add(string.Join("|", v));
                }
                if (sc.Count > 1)
                {
                    return GetProductSkuPropValues(sc,";");
                }
                return sc;

            }
        }

        public string ProductSkuPropName
        {
            get
            {

               return string.Join(",", this.ProductSkuProp.Select(x => x.PropName).Distinct());
            }
        }



        public IList<string> ProductSkuPropNames
        {
            get
            {
                IList<string> sc = new List<string>();
                IDictionary<string, ICollection<ProductSkuProp>> dict = new Dictionary<string, ICollection<ProductSkuProp>>();

                ILookup<int, string> lookup = this.ProductSkuProp.ToLookup(x => x.ItemCatPropId, x => x.ItemCatProp.ItemProp.GetPropValue(x.PropValue));

                foreach (IGrouping<int, string> item in lookup)
                {
                    var v = lookup[item.Key];
                    sc.Add(string.Join("|", v));
                }
                if (sc.Count > 1)
                {
                    return GetProductSkuPropValues(sc);
                }
                return sc;

            }
        }

        /**/
        /// <summary>
        /// 获取商品属性组合后的列表
        /// </summary>
        /// <param name="attrList">属性列表数组，数组内的成员以‘|’分隔</param>
        /// <returns>返回属性组合后的列表</returns>
        private static IList<string> GetProductSkuPropValues(IList<string> attrList, string separator = ",")
        {

            IList<string> productArray = new List<string>(attrList[0].Split('|'));

            for (int i = 1; i < attrList.Count; i++)
            {
                productArray = JoinPart(productArray, attrList[i].Split('|'), separator);
            }
            return productArray;
        }

        //笛卡尔乘积
        private static IList<string> JoinPart(IList<string> part1, string[] part2,string separator=",")
        {
            IList<string> result = new List<string>();
            foreach (string str1 in part1)
            {
                foreach (string str2 in part2)
                {
                    result.Add(str1 + separator + str2);
                }
            }
            return result;
        }

        //public System.Collections.Specialized.StringCollection ProductSkuPropValues
        //{
        //    get
        //    {
        //        StringCollection sc = new StringCollection();
        //        IDictionary<string,ICollection<ProductSkuProp>> dict =new Dictionary<string,ICollection<ProductSkuProp>>();
        //        foreach (var prop in this.ItemCat.ItemCatProp)
        //        {
        //            if (prop.ItemProp.IsSaleProp)
        //            {                
                       
        //                dict.Add(prop.ItemProp.Name, this.ProductSkuProp.Where(x=>x.ItemCatProp.ItemProp.Id==prop.ItemPropId).ToList());
                        
        //            }
        //        }
                
        //        foreach (KeyValuePair<string, ICollection<ProductSkuProp>> item in dict)
        //        {
        //            sc.Add(string.Join("|", item.Value.Select(x => x.PropValue)));
        //        }
        //        return sc;
        //    }
        //}



        #region ISearchableContent Members

        public string ToSearchContent(ITextExtractor textExtractor)
        {
            if (!string.IsNullOrEmpty(this.Desc))
            {
                return this.Desc;
            }
            if (!string.IsNullOrEmpty(this.Summary))
            {
                return this.Summary;
            }
            return ProductName;
        }

        public IList<CustomSearchField> GetCustomSearchFields()
        {
            var list= new List<CustomSearchField>();
            CustomSearchField field = new CustomSearchField("thumb", ThumbImageUrl, false, false);
            return list;
        }

        public SearchContent ToSearchContent()
        {
            SearchContent search = new SearchContent();
            search.Category = this.ItemCat.Name;
            search.DateCreated = this.Created;
            search.DateModified = this.Modified.HasValue ? this.Modified.Value : this.Created;
            search.Id = this.Id.ToString();
            if (!string.IsNullOrEmpty(this.Summary))
            {
                search.Summary = this.Summary;
            }
            else
            {
                if (!string.IsNullOrEmpty(this.Desc))
                {
                    search.Summary = Text.TruncateHtml(Desc);
                }
                else
                {
                    search.Summary = ProductName;
                }
               
            }
            search.Title = ProductName;
            search.Author = "嘉崇贸易";
            search.Path = "/product/item/" + search.Id;
            search.Boost = 1f;
            return search;
        }

        #endregion
    }


    internal partial class Product_Validation
    {
        [DisplayName("商品名称")]
        [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "名称不能为空")]
        public string ProductName { get; set; }


        [DisplayName("销售额")]
        public int? SaleNum { get; set; }

        [DisplayName("商品分类")]
        public int CId { get; set; }

       [DisplayName("商品品牌")]
       public int BrandId { get; set; }

       [DisplayName("成本价")]
       public decimal StandPrice { get; set; }

       [Range(1d, 100000000d, ErrorMessage = "请输入有效的市场价")]
       [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "市场价不能为空")]
       [DisplayName("市场价")]
       public decimal Price { get; set; }

       [Range(1d, 100000000d, ErrorMessage = "请输入有效的商城价")]
       [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "商城价不能为空")]
        [DisplayName("商城价")]
        public decimal ShopPrice { get; set; }
         [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "商品积分不能为空")]
        [Range(1, 100000, ErrorMessage = "请输入有效的商品积分")]
        [DisplayName("商品积分")]
        public int Points { get; set; }


        [DisplayName("上架时间")]
        public DateTime ListTime { get; set; }

        [DisplayName("下架时间")]
        public DateTime DeListTime { get; set; }

        [DataType(DataType.MultilineText)]
        [DisplayName("商品介绍")]
        public string Desc { get; set; }

        [DisplayName("商品图")]
        public string PicUrl { get; set; }

        [DisplayName("供应商")]
        public int SupplierId { get; set; }

        [DisplayName("计量单位")]
        public string Unit { get; set; }

        [DisplayName("商品货号")]
        public string StandCode { get; set; }
        [Range(1, 10000000, ErrorMessage = "请输入有效的商品重量")]
        [DisplayName("重量(克)")]
        public int Weight { get; set; }


        [Range(1, 10000000, ErrorMessage = "请输入有效的商品库存")]
        [DisplayName("商品库存")]
        public int CollectNum { get; set; }

        [Foolproof.RequiredIfTrue("IsRecommend", ErrorMessage = "推荐天数不能为空")]
        [Range(0,1000000,ErrorMessage="请输入有效的整数")]      
        [DisplayName("推荐天数")]
        public int RecommendDay { get; set; }


        [DisplayName("商品状态")]      
        public int Status { get; set; }


         [UIHint("ProductIs")]
        [DisplayName("发票")]        
        public bool HasInvoice { get; set; }

        [UIHint("ProductIs")]
        [DisplayName("保修")]
        public bool HasWarranty { get; set; }

        [DisplayName("热销商品")]
        public bool IsHot { get; set; }

        [UIHint("ProductYesNO")]
        [DisplayName("新商品")]
        public bool IsNew { get; set; }

        [DisplayName("虚拟商品")]
        [UIHint("ProductYesNO")]
        public bool IsVirtual { get; set; }

         [UIHint("ProductYesNO")]
        [DisplayName("推荐商品")]
        public bool IsRecommend { get; set; }

        [DataType(DataType.MultilineText)]
        [DisplayName("售后说明")]
        public string Warranty { get; set; }

        [DataType(DataType.MultilineText)]
        [DisplayName("包装清单")]
        public bool Package { get; set; }

         [DataType(DataType.MultilineText)]
        [DisplayName("规格参数")]
        public bool Specification { get; set; }

        [DisplayName("是否有折扣")]
         public bool HasDiscount { get; set; }

        [DisplayName("包装")]
        [UIHint("ProductIs")]
        public bool IsPackage { get; set; }


        [DisplayName("标题")]
        public string Title { get; set; }


        [DisplayName("关键字")]
        public string Keywords { get; set; }

        [DataType(DataType.MultilineText)]
        [DisplayName("描述")]
        public string Description { get; set; }


        [DisplayName("国家")]
        public int? Region { get; set; }

        [DisplayName("排序")]
        public int Sort { get; set; }
    }
}